package hunterxhunter.greedisland.events;

import java.awt.event.KeyEvent;
import framework.eea.StateBasedGame;
import framework.eea.event.Event;
import framework.eea.gui.JFrameGameContainer;
import framework.eea.interfaces.Action;

/**
 *
 * @author Markus Schr&ouml;der
 */
public class KeyPressedReleasedUseOneReleaseActionEvent extends Event {

    private int[] keyCodes;
    private boolean[] down;
    private Action[] pressedAction;
    private Action releasedAction;
    private boolean active = true;
    
    public KeyPressedReleasedUseOneReleaseActionEvent(int[] keyCodes, Action[] pressedAction, Action releasedAction) {
        super("KeyPressedReleasedUseActionEvent");
        this.keyCodes = keyCodes;
        this.pressedAction = pressedAction;
        this.releasedAction = releasedAction;
        down = new boolean[keyCodes.length];
    }
    
    private boolean atLeastOneDown() {
        for(boolean b : down) {
            if(b)
                return true;
        }
        return false;
    }
    
    private void allUp() {
        for(int i = 0; i < down.length; i++)
            down[i] = false;
    }
    
    @Override
    protected boolean performAction(JFrameGameContainer gc, StateBasedGame sb, int delta) {
        if(!isActive())
            return false;
        
        if(!sb.getKeyPressedQueue().isEmpty()) {
            KeyEvent pressed = sb.getKeyPressedQueue().peek();
            for(int i = 0; i < keyCodes.length; i++) {
                if(pressed.getKeyCode() == keyCodes[i]) {
                    pressedAction[i].update(gc, sb, delta, this);
                    down[i] = true;
                }
            }
        }
        if(!sb.getKeyReleasedQueue().isEmpty()) {
            KeyEvent released = sb.getKeyReleasedQueue().peek();
            for(int i = 0; i < keyCodes.length; i++) {
                if(released.getKeyCode() == keyCodes[i]) {
                    down[i] = false;
                    if(!atLeastOneDown()) {
                        releasedAction.update(gc, sb, delta, this);
                    }
                }
            }
        }
        return false;
    }

    /**
     * @return the active
     */
    public boolean isActive() {
        return active;
    }

    /**
     * @param active the active to set
     */
    public void setActive(boolean active) {
        this.active = active;
        if(!active) {
            allUp();
        }
    }

}
